import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { defaultRoutes } from '@/router/route';
import { LOGIN_URL, PUBLIC_PATH } from '@/constant';
import { setTitleFromRoute } from '@/utils/common';
import { useTokenStore } from '@/stores/token';

const router = createRouter({
    history: createWebHistory(PUBLIC_PATH),
    routes: defaultRoutes,
});

/** 全局前置守卫 */
router.beforeEach(async (to, from, next) => {
    console.log(to);
    NProgress.configure({ showSpinner: false });
    NProgress.start();
    // 验证是否需要登陆  不需要登陆直接放行
    if (to.meta.auth === false) {
        next();
    } else {
        // 验证登陆状态
        let login = useTokenStore().isLogin();
        console.log(login);
        if (login) {
            next();
        } else {
            next({ path: LOGIN_URL });
        }
    }
});

// 路由加载后
router.afterEach(() => {
    NProgress.done();
    setTitleFromRoute();
});

// 导出路由
export default router;
